home *** CD-ROM | disk | FTP | other *** search
/ Developer CD Series 1994 August: Tool Chest / Dev.CD Aug 94.toast / Tool Chest / Development Platforms / Macintosh Common Lisp Related / Lisp FAQ 21Sept93 / 3.Common Pitfalls < prev    next >
Encoding:
Internet Message Format  |  1993-09-21  |  34.5 KB  |  [TEXT/ttxt]

  1. Subject: FAQ: Lisp Frequently Asked Questions 3/7 [Monthly posting]
  2. Newsgroups: comp.lang.lisp,news.answers,comp.answers
  3. Summary: Common Pitfalls
  4. Distribution: world
  5. Followup-To: poster
  6. Reply-To: lisp-faq@think.com
  7. Approved: news-answers-request@MIT.Edu
  8.  
  9. Archive-name: lisp-faq/part3
  10. Last-Modified: Mon Sep 13 20:13:14 1993 by Mark Kantrowitz
  11. Version: 1.38
  12.  
  13. ;;; ****************************************************************
  14. ;;; Answers to Frequently Asked Questions about Lisp ***************
  15. ;;; ****************************************************************
  16. ;;; Written by Mark Kantrowitz and Barry Margolin
  17. ;;; lisp-faq-3.text -- 35273 bytes
  18.  
  19. This post contains Part 3 of the Lisp FAQ.
  20.  
  21. If you think of questions that are appropriate for this FAQ, or would
  22. like to improve an answer, please send email to us at lisp-faq@think.com.
  23.  
  24. This section contains a list of common pitfalls. Pitfalls are aspects
  25. of Common Lisp which are non-obvious to new programmers and often
  26. seasoned programmers as well.
  27.  
  28. Common Pitfalls (Part 3):
  29.  
  30.   [3-0]  Why does (READ-FROM-STRING "foobar" :START 3) return FOOBAR
  31.          instead of BAR?  
  32.   [3-1]  Why can't it deduce from (READ-FROM-STRING "foobar" :START 3)
  33.          that the intent is to specify the START keyword parameter
  34.          rather than the EOF-ERROR-P and EOF-VALUE optional parameters?   
  35.   [3-2]  Why can't I apply #'AND and #'OR?
  36.   [3-3]  I used a destructive function (e.g. DELETE, SORT), but it
  37.          didn't seem to work.  Why? 
  38.   [3-4]  After I NREVERSE a list, it's only one element long.  After I
  39.          SORT a list, it's missing things.  What happened? 
  40.   [3-5]  Why does (READ-LINE) return "" immediately instead of waiting
  41.          for me to type a line?  
  42.   [3-6]  I typed a form to the read-eval-print loop, but nothing happened. Why?
  43.   [3-7]  DEFMACRO doesn't seem to work.
  44.          When I compile my file, LISP warns me that my macros are undefined
  45.          functions, or complains "Attempt to call <function> which is 
  46.          defined as a macro.
  47.   [3-8]  Name conflict errors are driving me crazy! (EXPORT, packages)
  48.   [3-9]  Closures don't seem to work properly when referring to the
  49.          iteration variable in DOLIST, DOTIMES, DO and LOOP.
  50.   [3-10] What is the difference between FUNCALL and APPLY?
  51.   [3-11] Miscellaneous things to consider when debugging code.
  52.   [3-12] When is it right to use EVAL?
  53.   [3-13] Why does my program's behavior change each time I use it?
  54.   [3-14] When producing formatted output in Lisp, where should you put the
  55.          newlines (e.g., before or after the line, FRESH-LINE vs TERPRI,
  56.          ~& vs ~% in FORMAT)?
  57.   [3-15] I'm using DO to do some iteration, but it doesn't terminate. 
  58.   [3-16] My program works when interpreted but not when compiled!
  59.  
  60. Search for \[#\] to get to question number # quickly.
  61.  
  62. ----------------------------------------------------------------
  63. Subject: [3-0] Why does (READ-FROM-STRING "foobar" :START 3) return FOOBAR 
  64.                instead of BAR?
  65.  
  66. READ-FROM-STRING is one of the rare functions that takes both &OPTIONAL and
  67. &KEY arguments:
  68.  
  69.        READ-FROM-STRING string &OPTIONAL eof-error-p eof-value 
  70.                                &KEY :start :end :preserve-whitespace
  71.  
  72. When a function takes both types of arguments, all the optional
  73. arguments must be specified explicitly before any of the keyword
  74. arguments may be specified.  In the example above, :START becomes the
  75. value of the optional EOF-ERROR-P parameter and 3 is the value of the
  76. optional EOF-VALUE parameter.
  77.      
  78. ----------------------------------------------------------------
  79. Subject: [3-1] Why can't it deduce from (READ-FROM-STRING "foobar" :START 3) 
  80.       that the intent is to specify the START keyword parameter rather than
  81.       the EOF-ERROR-P and EOF-VALUE optional parameters?
  82.  
  83. In Common Lisp, keyword symbols are first-class data objects.  Therefore,
  84. they are perfectly valid values for optional parameters to functions.
  85. There are only four functions in Common Lisp that have both optional and
  86. keyword parameters (they are PARSE-NAMESTRING, READ-FROM-STRING,
  87. WRITE-LINE, and WRITE-STRING), so it's probably not worth adding a
  88. nonorthogonal kludge to the language just to make these functions slightly
  89. less confusing; unfortunately, it's also not worth an incompatible change
  90. to the language to redefine those functions to use only keyword arguments.
  91.      
  92. ----------------------------------------------------------------
  93. Subject: [3-2] Why can't I apply #'AND and #'OR?
  94.  
  95. Here's the simple, but not necessarily satisfying, answer: AND and OR are
  96. macros, not functions; APPLY and FUNCALL can only be used to invoke
  97. functions, not macros and special operators.
  98.  
  99. OK, so what's the *real* reason?  The reason that AND and OR are macros
  100. rather than functions is because they implement control structure in
  101. addition to computing a boolean value.  They evaluate their subforms
  102. sequentially from left/top to right/bottom, and stop evaluating subforms as
  103. soon as the result can be determined (in the case of AND, as soon as a
  104. subform returns NIL; in the case of OR, as soon as one returns non-NIL);
  105. this is referred to as "short circuiting" in computer language parlance.
  106. APPLY and FUNCALL, however, are ordinary functions; therefore, their
  107. arguments are evaluated automatically, before they are called.  Thus, were
  108. APPLY able to be used with #'AND, the short-circuiting would be defeated.
  109.  
  110. Perhaps you don't really care about the short-circuiting, and simply want
  111. the functional, boolean interpretation.  While this may be a reasonable
  112. interpretation of trying to apply AND or OR, it doesn't generalize to other
  113. macros well, so there's no obvious way to have the Lisp system "do the
  114. right thing" when trying to apply macros.  The only function associated
  115. with a macro is its expander function; this function accepts and returns
  116. and form, so it cannot be used to compute the value.
  117.  
  118. The Common Lisp functions EVERY and SOME can be used to get the
  119. functionality you intend when trying to apply #'AND and #'OR.  For
  120. instance, the erroneous form:
  121.  
  122.    (apply #'and *list*)
  123.  
  124. can be translated to the correct form:
  125.  
  126.    (every #'identity *list*)
  127.  
  128. ----------------------------------------------------------------
  129. Subject: [3-3] I used a destructive function (e.g. DELETE, SORT), but 
  130.                it didn't seem to work.  Why?
  131.  
  132. I assume you mean that it didn't seem to modify the original list.  There
  133. are several possible reasons for this.  First, many destructive functions
  134. are not *required* to modify their input argument, merely *allowed* to; in
  135. some cases, the implementation may determine that it is more efficient to
  136. construct a new result than to modify the original (this may happen in Lisp
  137. systems that use "CDR coding", where RPLACD may have to turn a CDR-NEXT or
  138. CDR-NIL cell into a CDR-NORMAL cell), or the implementor may simply not
  139. have gotten around to implementing the destructive version in a truly
  140. destructive manner.  Another possibility is that the nature of the change
  141. that was made involves removing elements from the front of a list; in this
  142. case, the function can simply return the appropriate tail of the list,
  143. without actually modifying the list. And example of this is:
  144.      
  145.    (setq *a* (list 3 2 1))
  146.    (delete 3 *a*) => (2 1)
  147.    *a* => (3 2 1)
  148.  
  149. Similarly, when one sorts a list, SORT may destructively rearrange the
  150. pointers (cons cells) that make up the list. SORT then returns the cons
  151. cell that now heads the list; the original cons cell could be anywhere in
  152. the list. The value of any variable that contained the original head of the
  153. list hasn't changed, but the contents of that cons cell have changed
  154. because SORT is a destructive function:
  155.  
  156.    (setq *a* (list 2 1 3))
  157.    (sort *a* #'<) => (1 2 3)
  158.    *a* => (2 3)     
  159.  
  160. In both cases, the remedy is the same: store the result of the
  161. function back into the place whence the original value came, e.g.
  162.  
  163.    (setq *a* (delete 3 *a*))
  164.    *a* => (2 1)
  165.  
  166. Why don't the destructive functions do this automatically?  Recall
  167. that they are just ordinary functions, and all Lisp functions are
  168. called by value. They see the value of the argument, not the argument
  169. itself. Therefore, these functions do not know where the lists they
  170. are given came from; they are simply passed the cons cell that
  171. represents the head of the list. Their only obligation is to return
  172. the new cons cell that represents the head of the list. Thus
  173. "destructive" just means that the function may munge the list by
  174. modifying the pointers in the cars and cdrs of the list's cons cells.
  175. This can be more efficient, if one doesn't care whether the original
  176. list gets trashed or not.
  177.  
  178. One thing to be careful about when doing this (storing the result back
  179. into the original location) is that the original list might be
  180. referenced from multiple places, and all of these places may need to
  181. be updated.  For instance:
  182.  
  183.    (setq *a* (list 3 2 1))
  184.    (setq *b* *a*)
  185.    (setq *a* (delete 3 *a*))
  186.    *a* => (2 1)
  187.    *b* => (3 2 1) ; *B* doesn't "see" the change
  188.    (setq *a* (delete 1 *a*))
  189.    *a* => (2)
  190.    *b* => (3 2) ; *B* sees the change this time, though
  191.  
  192. One may argue that destructive functions could do what you expect by
  193. rearranging the CARs of the list, shifting things up if the first element
  194. is being deleted, as they are likely to do if the argument is a vector
  195. rather than a list.  In many cases they could do this, although it would
  196. clearly be slower.  However, there is one case where this is not possible:
  197. when the argument or value is NIL, and the value or argument, respectively,
  198. is not.  It's not possible to transform the object referenced from the
  199. original cell from one data type to another, so the result must be stored
  200. back.  Here are some examples:
  201.  
  202.    (setq *a* (list 3 2 1))
  203.    (delete-if #'numberp *a) => NIL
  204.    *a* => (3 2 1)
  205.    (setq *a* nil *b* '(1 2 3))
  206.    (nconc *a* *b*) => (1 2 3)
  207.    *a* => NIL
  208.  
  209. The names of most destructure functions (except for sort, delete,
  210. rplaca, rplacd, and setf of accessor functions) have the prefix N.
  211.  
  212. In summary, the two common problems to watch out for when using
  213. destructive functions are:
  214.  
  215.    1. Forgetting to store the result back. Even though the list
  216.       is modified in place, it is still necessary to store the
  217.       result of the function back into the original location, e.g.,
  218.            (setq foo (delete 'x foo))
  219.  
  220.       If the original list was stored in multiple places, you may
  221.       need to store it back in all of them, e.g.
  222.            (setq bar foo)
  223.            ...
  224.            (setq foo (delete 'x foo))
  225.            (setq bar foo)
  226.  
  227.    2. Sharing structure that gets modified. If it is important
  228.       to preserve the shared structure, then you should either
  229.       use a nondestructive operation or copy the structure first
  230.       using COPY-LIST or COPY-TREE.
  231.            (setq bar (cdr foo))
  232.            ...
  233.            (setq foo (sort foo #'<))
  234.            ;;; now it's not safe to use BAR
  235.  
  236. Note that even nondestructive functions, such as REMOVE, and UNION,
  237. can return a result which shares structure with an argument. 
  238. Nondestructive functions don't necessarily copy their arguments; they
  239. just don't modify them.
  240.      
  241. ----------------------------------------------------------------
  242. Subject: [3-4] After I NREVERSE a list, it's only one element long.  
  243.                After I SORT a list, it's missing things.  What happened?
  244.  
  245. These are particular cases of the previous question.  Many NREVERSE and
  246. SORT implementations operate by rechaining all the CDR links in the list's
  247. backbone, rather than by replacing the CARs.  In the case of NREVERSE, this
  248. means that the cons cell that was originally first in the list becomes the
  249. last one.  As in the last question, the solution is to store the result
  250. back into the original location.
  251.      
  252. ----------------------------------------------------------------
  253. Subject: [3-5] Why does (READ-LINE) return "" immediately instead of 
  254.                waiting for me to type a line?
  255.  
  256. Many Lisp implementations on line-buffered systems do not discard the
  257. newline that the user must type after the last right parenthesis in order
  258. for the line to be transmitted from the OS to Lisp.  Lisp's READ function
  259. returns immediately after seeing the matching ")" in the stream.  When
  260. READLINE is called, it sees the next character in the stream, which is a
  261. newline, so it returns an empty line.  If you were to type "(read-line)This
  262. is a test" the result would be "This is a test".
  263.  
  264. The simplest solution is to use (PROGN (CLEAR-INPUT) (READ-LINE)).  This
  265. discards the buffered newline before reading the input.  However, it would
  266. also discard any other buffered input, as in the "This is a test" example
  267. above; some implementation also flush the OS's input buffers, so typeahead
  268. might be thrown away.
  269.  
  270. ----------------------------------------------------------------
  271. Subject: [3-6] I typed a form to the read-eval-print loop, but 
  272.                nothing happened. Why?
  273.  
  274. There's not much to go on here, but a common reason is that you haven't
  275. actually typed a complete form.  You may have typed a doublequote, vertical
  276. bar, "#|" comment beginning, or left parenthesis that you never matched
  277. with another doublequote, vertical bar, "|#", or right parenthesis,
  278. respectively.  Try typing a few right parentheses followed by Return.
  279.  
  280. ----------------------------------------------------------------
  281. Subject: [3-7]  DEFMACRO doesn't seem to work. 
  282.                 When I compile my file, LISP warns me that my macros
  283.                 are undefined functions, or complains 
  284.                   "Attempt to call <function> which is defined as a macro."
  285.  
  286. When you evaluate a DEFMACRO form or proclaim a function INLINE, it
  287. doesn't go back and update code that was compiled under the old
  288. definition. When redefining a macro, be sure to recompile any
  289. functions that use the macro. Also be sure that the macros used in a
  290. file are defined before any forms in the same file that use them.
  291.  
  292. Certain forms, including LOAD, SET-MACRO-CHARACTER, and
  293. REQUIRE, are not normally evaluated at compile time. Common Lisp
  294. requires that macros defined in a file be used when compiling later
  295. forms in the file. If a Lisp doesn't follow the standard, it may be
  296. necessary to wrap an EVAL-WHEN form around the macro definition.
  297.  
  298. Most often the "macro was previously called as a function" problem
  299. occurs when files were compiled/loaded in the wrong order. For
  300. example, developers may add the definition to one file, but use it in
  301. a file which is compiled/loaded before the definition. To work around
  302. this problem, one can either fix the modularization of the system, or
  303. manually recompile the files containing the forward references to macros.
  304.  
  305. Also, if your macro calls functions at macroexpand time, those functions
  306. may need to be in an EVAL-WHEN. For example,
  307.  
  308.     (defun some-function (x)
  309.       x)
  310.  
  311.     (defmacro some-macro (y)
  312.       (let ((z (some-function y)))
  313.         `(print ',z)))
  314.  
  315. If the macros are defined in a file you require, make sure your
  316. require or load statement is in an appropriate EVAL-WHEN. Many people
  317. avoid all this nonsense by making sure to load all their files before
  318. compiling them, or use a system facility (or just a script file) that
  319. loads each file before compiling the next file in the system.
  320.  
  321. ----------------------------------------------------------------
  322. Subject: [3-8]  Name conflict errors are driving me crazy! (EXPORT, packages)
  323.  
  324. If a package tries to export a symbol that's already defined, it will
  325. report an error. You probably tried to use a function only to discover
  326. that you'd forgotten to load its file. The failed attempt at using the
  327. function caused its symbol to be interned. So now, when you try to
  328. load the file, you get a conflict. Unfortunately, understanding and
  329. correcting the code which caused the export problem doesn't make those
  330. nasty error messages go away. That symbol is still interned where it
  331. shouldn't be. Use unintern to remove the symbol from a package before
  332. reloading the file. Also, when giving arguments to REQUIRE or package
  333. functions, use strings or keywords, not symbols: (find-package "FOO"),
  334. (find-package :foo). 
  335.  
  336. A sometimes useful technique is to rename (or delete) a package
  337. that is "too messed up".  Then you can reload the relevant files
  338. into a "clean" package.
  339.  
  340. ----------------------------------------------------------------
  341. Subject: [3-9]  Closures don't seem to work properly when referring to the
  342.                 iteration variable in DOLIST, DOTIMES, DO and LOOP.
  343.  
  344. DOTIMES, DOLIST, DO and LOOP all use assignment instead of binding to
  345. update the value of the iteration variables. So something like
  346.    
  347.    (let ((l nil))
  348.      (dotimes (n 10)
  349.        (push #'(lambda () n)
  350.          l)))
  351.  
  352. will produce 10 closures over the same value of the variable N. To
  353. avoid this problem, you'll need to create a new binding after each
  354. assignment: 
  355.  
  356.    (let ((l nil))
  357.      (dotimes (n 10)
  358.     (let ((n n))
  359.       (push #'(lambda () n)
  360.         l))))
  361.  
  362. Then each closure will be over a new binding of n.
  363.  
  364. This is one reason why programmers who use closures prefer MAPC and
  365. MAPCAR to DOLIST.
  366.  
  367. ----------------------------------------------------------------
  368. Subject: [3-10] What is the difference between FUNCALL and APPLY?
  369.  
  370. FUNCALL is useful when the programmer knows the length of the argument
  371. list, but the function to call is either computed or provided as a
  372. parameter.  For instance, a simple implementation of MEMBER-IF (with
  373. none of the fancy options) could be written as:
  374.  
  375. (defun member-if (predicate list)
  376.   (do ((tail list (cdr tail)))
  377.       ((null tail))
  378.    (when (funcall predicate (car tail))
  379.      (return-from member-if tail))))
  380.  
  381. The programmer is invoking a caller-supplied function with a known
  382. argument list.
  383.  
  384. APPLY is needed when the argument list itself is supplied or computed.
  385. Its last argument must be a list, and the elements of this list become
  386. individual arguments to the function.  This frequently occurs when a
  387. function takes keyword options that will be passed on to some other
  388. function, perhaps with application-specific defaults inserted.  For
  389. instance:
  390.  
  391. (defun open-for-output (pathname &rest open-options)
  392.   (apply #'open pathname :direction :output open-options))
  393.  
  394. FUNCALL could actually have been defined using APPLY:
  395.  
  396. (defun funcall (function &rest arguments)
  397.   (apply function arguments))
  398.  
  399. ----------------------------------------------------------------
  400. Subject: [3-11] Miscellaneous things to consider when debugging code.
  401.  
  402. This question lists a variety of problems to watch out for when
  403. debugging code. This is sort of a catch-all question for problems too
  404. small to merit a question of their own. See also question [1-3] for
  405. some other common problems.
  406.  
  407. Functions:
  408.  
  409.   * (flet ((f ...)) (eq #'f #'f)) can return false.
  410.  
  411.   * The function LIST-LENGTH is not a faster, list-specific version
  412.     of the sequence function LENGTH.  It is list-specific, but it's
  413.     slower than LENGTH because it can handle circular lists.
  414.  
  415.   * Don't confuse the use of LISTP and CONSP. CONSP tests for the
  416.     presence of a cons cell, but will return NIL when called on NIL.
  417.     LISTP could be defined as (defun listp (x) (or (null x) (consp x))).
  418.  
  419.   * Use the right test for equality: 
  420.         EQ      tests if the objects are identical -- numbers with the
  421.                 same value need not be EQ, nor are two similar lists
  422.                 necessarily EQ. Similarly for characters and strings.
  423.                 For instance, (let ((x 1)) (eq x x)) is not guaranteed
  424.                 to return T.
  425.         EQL     Like EQ, but is also true if the arguments are numbers
  426.                 of the same type with the same value or character objects
  427.                 representing the same character. (eql -0.0 0.0) is not
  428.                 guaranteed to return T.
  429.         EQUAL   Tests if the arguments are structurally isomorphic, using
  430.                 EQUAL to compare components that are conses, bit-vectors, 
  431.                 strings or pathnames, and EQ for all other data objects
  432.                 (except for numbers and characters, which are compared
  433.                 using EQL). Except for strings and bit-vectors, arrays
  434.                 are EQUAL only if they are EQ.
  435.         EQUALP  Like EQUAL, but ignores type differences when comparing 
  436.                 numbers and case differences when comparing characters.
  437.         =       Compares the values of two numbers even if they are of
  438.                 different types.
  439.         CHAR=   Case-sensitive comparison of characters.
  440.         CHAR-EQUAL      Case-insensitive comparison of characters.
  441.         STRING= Compares two strings, checking if they are identical.
  442.                 It is case sensitive.
  443.         STRING-EQUAL  Like STRING=, but case-insensitive.
  444.  
  445.   * Some destructive functions that you think would modify CDRs might
  446.     modify CARs instead.  (E.g., NREVERSE.)
  447.  
  448.   * READ-FROM-STRING has some optional arguments before the
  449.     keyword parameters.  If you want to supply some keyword
  450.     arguments, you have to give all of the optional ones too.
  451.  
  452.   * If you use the function READ-FROM-STRING, you should probably bind
  453.     *READ-EVAL* to NIL. Otherwise an unscrupulous user could cause a
  454.     lot of damage by entering 
  455.         #.(shell "cd; rm -R *")
  456.     at a prompt.
  457.  
  458.   * Only functional objects can be funcalled in CLtL2, so a lambda
  459.     expression '(lambda (..) ..) is no longer suitable. Use
  460.     #'(lambda (..) ..) instead. If you must use '(lambda (..) ..),
  461.     coerce it to type FUNCTION first using COERCE.
  462.  
  463. Methods:
  464.  
  465.   * PRINT-OBJECT methods can make good code look buggy. If there is a
  466.     problem with the PRINT-OBJECT methods for one of your classes, it
  467.     could make it seem as though there were a problem with the object.
  468.     It can be very annoying to go chasing through your code looking for
  469.     the cause of the wrong value, when the culprit is just a bad
  470.     PRINT-OBJECT method.
  471.  
  472. Initialization:
  473.  
  474.   * Don't count on array elements being initialized to NIL, if you don't
  475.     specify an :initial-element argument to MAKE-ARRAY. For example,
  476.          (make-array 10) => #(0 0 0 0 0 0 0 0 0 0)
  477.  
  478. Iteration vs closures:
  479.  
  480.   * DO and DO* update the iteration variables by assignment; DOLIST and
  481.     DOTIMES are allowed to use assignment (rather than a new binding).
  482.     (All CLtL1 says of DOLIST and DOTIMES is that the variable "is
  483.     bound" which has been taken as _not_ implying that there will be
  484.     separate bindings for each iteration.) 
  485.  
  486.     Consequently, if you make closures over an iteration variable
  487.     in separate iterations they may nonetheless be closures over
  488.     the same variable and hence will all refer to the same value
  489.     -- whatever value the variable was given last.  For example,
  490.         (let ((fns '()))
  491.           (do ((x '(1 2) (cdr x)))
  492.               ((null x))
  493.             (push #'(lambda () x)
  494.                   fns))
  495.           (mapcar #'funcall (reverse fns)))
  496.     returns (nil nil), not (1 2), not even (2 2). Thus 
  497.          (let ((l nil)) 
  498.            (dolist (a '(1 2 3) l) 
  499.              (push #'(lambda () a)
  500.                    l)))
  501.     returns a list of three closures closed over the same bindings, whereas
  502.          (mapcar #'(lambda (a) #'(lambda () a)) '(1 2 3))
  503.     returns a list of closures over distinct bindings.
  504.  
  505. Defining Variables and Constants:
  506.  
  507.   * (defvar var init) assigns to the variable only if it does not
  508.     already have a value.  So if you edit a DEFVAR in a file and
  509.     reload the file only to find that the value has not changed,
  510.     this is the reason.  (Use DEFPARAMETER if you want the value
  511.     to change upon reloading.) DEFVAR is used to declare a variable
  512.     that is changed by the program; DEFPARAMETER is used to declare
  513.     a variable that is normally constant, but which can be changed
  514.     to change the functioning of a program.
  515.  
  516.   * DEFCONSTANT has several potentially unexpected properties:
  517.  
  518.      - Once a name has been declared constant, it cannot be used a
  519.        the name of a local variable (lexical or special) or function
  520.        parameter.  Really.  See page 87 of CLtL2.
  521.  
  522.      - A DEFCONSTANT cannot be re-evaluated (eg, by reloading the
  523.        file in which it appears) unless the new value is EQL to the
  524.        old one.  Strictly speaking, even that may not be allowed.
  525.        (DEFCONSTANT is "like DEFPARAMETER" and hence does an
  526.        assignment, which is not allowed if the name has already
  527.        been declared constant by DEFCONSTANT.)
  528.  
  529.        Note that this makes it difficult to use anything other
  530.        than numbers, symbols, and characters as constants.       
  531.  
  532.      - When compiling (DEFCONSTANT name form) in a file, the form
  533.        may be evaluated at compile-time, load-time, or both.  
  534.  
  535.        (You might think it would be evaluated at compile-time and
  536.        the _value_ used to obtain the object at load-time, but it
  537.        doesn't have to work that way.)
  538.  
  539. Declarations:
  540.  
  541.   * You often have to declare the result type to get the most
  542.     efficient arithmetic.  Eg, 
  543.  
  544.        (the fixnum (+ (the fixnum e1) (the fixnum e2)))
  545.  
  546.      rather than
  547.  
  548.        (+ (the fixnum e1) (the fixnum e2))
  549.  
  550.   * Declaring the iteration variable of a DOTIMES to have type FIXNUM
  551.     does not guarantee that fixnum arithmetic will be used.  That is,
  552.     implementations that use fixnum-specific arithmetic in the presence
  553.     of appropriate declaration may not think _this_ declaration is
  554.     sufficient.  It may help to declare that the limit is also a
  555.     fixnum, or you may have to write out the loop as a DO and add
  556.     appropriate declarations for each operation involved.
  557.  
  558. FORMAT related errors:
  559.  
  560.   * When printing messages about files, filenames like foo~ (a GNU-Emacs
  561.     backup file) may cause problems with poorly coded FORMAT control
  562.     strings.
  563.  
  564.   * Beware of using an ordinary string as the format string,
  565.     i.e., (format t string), rather than (format t "~A" string).
  566.  
  567. Miscellaneous:
  568.  
  569.   * Be careful of circular lists and shared list structure. 
  570.  
  571.   * Watch out for macro redefinitions.
  572.  
  573.   * A NOTINLINE may be needed if you want SETF of SYMBOL-FUNCTION to
  574.     affect calls within a file.  (See CLtL2, page 686.)
  575.  
  576.   * When dividing two numbers, beware of creating a rational number where
  577.     you intended to get an integer or floating point number. Use TRUNCATE
  578.     or ROUND to get an integer and FLOAT to ensure a floating point
  579.     number. This is a major source of errors when porting ZetaLisp or C
  580.     code to Common Lisp.
  581.  
  582.   * If your code doesn't work because all the symbols are mysteriously
  583.     in the keyword package, one of your comments has a colon (:) in
  584.     it instead of a semicolon (;).
  585.  
  586. ----------------------------------------------------------------
  587. Subject: [3-12] When is it right to use EVAL?
  588.  
  589. Hardly ever.  Any time you think you need to use EVAL, think hard about it.
  590. EVAL is useful when implementing a facility that provides an external
  591. interface to the Lisp interpreter.  For instance, many Lisp-based editors
  592. provide a command that prompts for a form and displays its value.
  593. Inexperienced macro writers often assume that they must explicitly EVAL the
  594. subforms that are supposed to be evaluated, but this is not so; the correct
  595. way to write such a macro is to have it expand into another form that has
  596. these subforms in places that will be evaluated by the normal evaluation
  597. rules.  Explicit use of EVAL in a macro is likely to result in one of two
  598. problems: the dreaded "double evaluation" problem, which may not show up
  599. during testing if the values of the expressions are self-evaluating
  600. constants (such as numbers); or evaluation at compile time rather than
  601. runtime.  For instance, if Lisp didn't have IF and one desired to write it,
  602. the following would be wrong:
  603.  
  604.    (defmacro if (test then-form &optional else-form)
  605.      ;; this evaluates all the subforms at compile time, and at runtime
  606.      ;; evaluates the results again.
  607.      `(cond (,(eval test) ,(eval then-form))
  608.             (t ,(eval else-form))))
  609.  
  610.    (defmacro if (test then-form &optional else-form)
  611.      ;; this double-evaluates at run time
  612.      `(cond ((eval ,test) (eval ,then-form))
  613.             (t (eval ,else-form)))
  614.  
  615. This is correct:
  616.  
  617.    (defmacro if (test then-form &optional else-form)
  618.      `(cond (,test ,then-form)
  619.             (t ,else-form)))
  620.  
  621. The following question (taken from an actual post) is typical of the
  622. kind of question asked by a programmer who is misusing EVAL:
  623.  
  624.    I would like to be able to quote all the atoms except the first in a
  625.    list of atoms.  The purpose is to allow a function to be read in and
  626.    evaluated as if its arguments had been quoted.
  627.  
  628. This is the wrong approach to solving the problem. Instead, he should
  629. APPLY the CAR of the form to the CDR of the form. Then quoting the
  630. rest of the form is unnecessary. But one wonders why he's trying to
  631. solve this problem in the first place, since the toplevel REP loop
  632. already involves a call to EVAL. One gets the feeling that if we knew
  633. more about what he's trying to accomplish, we'd be able to point out a
  634. more appropriate solution that uses neither EVAL nor APPLY.
  635.  
  636. On the other hand, EVAL can sometimes be necessary when the only portable
  637. interface to an operation is a macro. 
  638.  
  639. ----------------------------------------------------------------
  640. Subject: [3-13] Why does my program's behavior change each time I use it?
  641.  
  642. Most likely your program is altering itself, and the most common way this
  643. may happen is by performing destructive operations on embedded constant
  644. data structures.  For instance, consider the following:
  645.  
  646.    (defun one-to-ten-except (n)
  647.      (delete n '(1 2 3 4 5 6 7 8 9 10)))
  648.    (one-to-ten-except 3) => (1 2 4 5 6 7 8 9 10)
  649.    (one-to-ten-except 5) => (1 2 4 6 7 8 9 10) ; 3 is missing
  650.  
  651. The basic problem is that QUOTE returns its argument, *not* a copy of
  652. it. The list is actually a part of the lambda expression that is in
  653. ONE-TO-TEN-EXCEPT's function cell, and any modifications to it (e.g., by
  654. DELETE) are modifications to the actual object in the function definition.
  655. The next time that the function is called, this modified list is used.
  656.  
  657. In some implementations calling ONE-TO-TEN-EXCEPT may even result in
  658. the signalling of an error or the complete aborting of the Lisp process.  Some
  659. Lisp implementations put self-evaluating and quoted constants onto memory
  660. pages that are marked read-only, in order to catch bugs such as this.
  661. Details of this behavior may vary even within an implementation,
  662. depending on whether the code is interpreted or compiled (perhaps due to
  663. inlined DEFCONSTANT objects or constant folding optimizations).
  664.  
  665. All of these behaviors are allowed by the draft ANSI Common Lisp
  666. specification, which specifically states that the consequences of modifying
  667. a constant are undefined (X3J13 vote CONSTANT-MODIFICATION:DISALLOW).
  668.  
  669. To avoid these problems, use LIST to introduce a list, not QUOTE. QUOTE
  670. should be used only when the list is intended to be a constant which
  671. will not be modified.  If QUOTE is used to introduce a list which will
  672. later be modified, use COPY-LIST to provide a fresh copy.
  673.  
  674. For example, the following should all work correctly:
  675.  
  676.    o  (remove 4 (list 1 2 3 4 1 3 4 5))
  677.    o  (remove 4 '(1 2 3 4 1 3 4 5))   ;; Remove is non-destructive.
  678.    o  (delete 4 (list 1 2 3 4 1 3 4 5))
  679.    o  (let ((x (list 1 2 4 1 3 4 5)))
  680.         (delete 4 x))
  681.    o  (defvar *foo* '(1 2 3 4 1 3 4 5))
  682.       (delete 4 (copy-list *foo*))
  683.       (remove 4 *foo*)
  684.       (let ((x (copy-list *foo*)))
  685.          (delete 4 x))
  686.  
  687. The following, however, may not work as expected:
  688.  
  689.    o  (delete 4 '(1 2 3 4 1 3 4 5))
  690.  
  691. Note that similar issues may also apply to hard-coded strings. If you
  692. want to modify elements of a string, create the string with MAKE-STRING.
  693.  
  694. ----------------------------------------------------------------
  695. Subject: [3-14]  When producing formatted output in Lisp, where should you 
  696.         put the newlines (e.g., before or after the line, FRESH-LINE vs TERPRI,
  697.         ~& vs ~% in FORMAT)?
  698.  
  699.  
  700. Where possible, it is desirable to write functions that produce output
  701. as building blocks. In contrast with other languages, which either
  702. conservatively force a newline at various times or require the program
  703. to keep track of whether it needs to force a newline, the Lisp I/O
  704. system keeps track of whether the most recently printed character was
  705. a newline or not. The function FRESH-LINE outputs a newline only if
  706. the stream is not already at the beginning of a line.  TERPRI forces a
  707. newline irrespective of the current state of the stream. These
  708. correspond to the ~& and ~% FORMAT directives, respectively. (If the
  709. Lisp I/O system can't determine whether it's physically at the
  710. beginning of a line, it assumes that a newline is needed, just in case.)
  711.  
  712. Thus, if you want formatted output to be on a line of its own, start
  713. it with ~& and end it with ~%. (Some people will use a ~& also at the
  714. end, but this isn't necessary, since we know a priori that we're not
  715. at the beginning of a line. The only exception is when ~& follows a
  716. ~A, to prevent a double newline when the argument to the ~A is a
  717. formatted string with a newline at the end.) For example, the
  718. following routine prints the elements of a list, N elements per line,
  719. and then prints the total number of elements on a new line:
  720.  
  721.    (defun print-list (list &optional (elements-per-line 10))
  722.      (fresh-line)
  723.      (loop for i upfrom 1
  724.            for element in list do
  725.        (format t "~A ~:[~;~%~]" element (zerop (mod i elements-per-line))))
  726.      (format t "~&~D~%" (length list)))
  727.  
  728. ----------------------------------------------------------------
  729. Subject: [3-15] I'm using DO to do some iteration, but it doesn't terminate. 
  730.  
  731. Your code probably looks something like
  732.    (do ((sublist list (cdr list))
  733.         ..)
  734.        ((endp sublist)
  735.         ..)
  736.      ..)
  737. or maybe
  738.    (do ((index start (+ start 2))
  739.         ..)
  740.        ((= index end)
  741.         ..)
  742.      ..)
  743.  
  744. The problem is caused by the (cdr list) and the (+ start 2) in the
  745. first line. You're using the original list and start index instead of
  746. the working sublist or index. Change them to (cdr sublist) and 
  747. (+ index 2) and your code should start working.
  748.  
  749. ----------------------------------------------------------------
  750. Subject: [3-16] My program works when interpreted but not when compiled!
  751.  
  752. Look for problems with your macro definitions, such as a macro that is
  753. missing a quote. When compiled, this definition essentially becomes a
  754. constant. But when interpreted, the body of the macro is executed each
  755. time the macro is called.
  756.  
  757. For example, in Allegro CL the following code will behave differently
  758. when interpreted and compiled:
  759.   (defvar x 10)
  760.   (defmacro foo () (incf x))
  761.   (defun bar () (+ (foo) (foo)))
  762. Putting a quote before the (incf x) in the definition of foo fixes the
  763. problem. 
  764.  
  765. If you use (SETF (SYMBOL-FUNCTION 'foo) ...) to change the definition
  766. of a built-in Lisp function named FOO, be aware that this may not work
  767. correctly (i.e., as desired) in compiled code in all Lisps. In some
  768. Lisps, the compiler treats certain symbols in the LISP package
  769. specially, ignoring the function definition. If you want to redefine a
  770. standard function try proclaiming/declaring it NOTINLINE prior to
  771. compiling any use that should go through the function cell. (Note that
  772. this is not guarranteed to work, since X3J13 has stated that it is not
  773. permitted to redefine any of the standard functions).
  774.  
  775. ----------------------------------------------------------------
  776. ;;; *EOF*
  777.